import {defineStore} from 'pinia';
import {ref, computed} from 'vue';
import type {User} from "@/models/user";

// 定义存储状态接口
interface UserState {
    user: User | null;
}

// 创建用户存储
export const useUserStore = defineStore('user', () => {
    // 初始化状态，从localStorage读取
    const initState = (): UserState => {
        const storedUser = localStorage.getItem('user');
        const storedToken = localStorage.getItem('token');

        if (storedUser && storedToken) {
            try {
                return {
                    user: JSON.parse(storedUser),
                };
            } catch (error) {
                console.error('Failed to parse user data from localStorage', error);
            }
        }

        return {
            user: null,
        };
    };

    // 状态
    const state = ref<UserState>(initState());

    // 计算属性
    const isAdmin = computed(() => state.value.user?.userRole === 1);

    /**
     * 获取当前用户信息
     * @returns 当前登录用户信息或null
     */
    const getCurrentUser = (): User | null => {
        return state.value.user;
    };

    // 操作方法
    /**
     * 保存登录信息
     * @param user 用户信息
     * @param token 令牌
     */
    const saveLoginInfo = (user: User) => {
        state.value.user = user;

        // 持久化到本地存储
        localStorage.setItem('user', JSON.stringify(user));
    };

    /**
     * 退出登录
     */
    const logout = () => {
        state.value.user = null;

        // 清除本地存储
        localStorage.clear();
    };

    /**
     * 更新用户信息
     * @param data 要更新的用户数据
     */
    const updateUserInfo = (data: Partial<User>) => {
        if (state.value.user) {
            state.value.user = {...state.value.user, ...data};
            localStorage.setItem('user', JSON.stringify(state.value.user));
        }
    };

    /**
     * 清除所有用户信息
     */
    const clearUserInfo = () => {
        state.value.user = null;
        localStorage.removeItem('user');
        localStorage.clear();
    };

    return {
        // 状态
        state,
        // 计算属性
        isAdmin,
        // 方法
        saveLoginInfo,
        logout,
        updateUserInfo,
        clearUserInfo,
        getCurrentUser,
    };
});



